package com.io.commonlib.helper

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences

/**
 * Description:封装SharedPreferences相关的方法
 * 2021-05-20 10:05
 * @author LiuMin
 */
class SPHelper {
    private val TAG = SPHelper::class.java.simpleName
    private var mSpf: SharedPreferences? = null
    private var mEditor: SharedPreferences.Editor? = null

    companion object{
        private var instance:SPHelper? = null
        fun getInstance(ctx:Context, spFileName:String): SPHelper?{
            instance?.let {
                return it
            } ?: let {
                instance = SPHelper(ctx, spFileName)
                return instance
            }
        }
    }

    @SuppressLint("CommitPrefEdits")
    private constructor(ctx:Context, spFileName:String){
        if(mSpf ==  null){
            if(spFileName.isNotEmpty()){
                mSpf = ctx.getSharedPreferences(spFileName, Context.MODE_PRIVATE)
                mEditor = mSpf?.edit()
            } else {
                LogHelper.d(TAG, "init--spFileName为空")
            }
        }
    }

    fun getString(key:String, defaultValue:String): String?{
        return mSpf?.getString(key, defaultValue)
    }

    fun putString(key:String, value:String){
        mEditor?.putString(key, value)?.commit()
    }

    fun getInt(key:String, defaultValue:Int): Int?{
        return mSpf?.getInt(key, defaultValue)
    }

    fun putInt(key:String, value:Int){
        mEditor?.putInt(key, value)?.commit()
    }

    fun getLong(key:String, defaultValue:Long): Long?{
        return mSpf?.getLong(key, defaultValue)
    }

    fun putLong(key:String, value:Long){
        mEditor?.putLong(key, value)?.commit()
    }

    fun getBoolean(key:String, defaultValue:Boolean): Boolean?{
        return mSpf?.getBoolean(key, defaultValue)
    }

    fun putBoolean(key:String, value:Boolean){
        mEditor?.putBoolean(key, value)?.commit()
    }
}